package com.wude.guild;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.mc.developmentkit.utils.ToastUtil;
import com.umeng.analytics.MobclickAgent;
import com.wude.bean.UserInfo;
import com.wude.guild.servercore.mints.TitleBaseActivity;
import com.wude.http.HttpCom;
import com.wude.http.HttpUtils;
import com.wude.tools.Utils;
import com.wude.tools.ViewUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

@SuppressLint("HandlerLeak")
public class LoginActivity extends TitleBaseActivity implements TextWatcher, View.OnClickListener {
    @BindView(R.id.ed_hao)
    EditText edHao;
    @BindView(R.id.ed_pass)
    EditText edPass;
    @BindView(R.id.hao_delete)
    ImageView haoDelete;
    @BindView(R.id.pass_delete)
    ImageView passDelete;
    @BindView(R.id.tv_loginType)
    TextView tvLoginType;
    @BindView(R.id.ll_authCode)
    LinearLayout ll_authCode;
    @BindView(R.id.ll_password)
    LinearLayout ll_password;
    @BindView(R.id.getAuthCode)
    TextView getAuthCode;
    @BindView(R.id.te_login)
    TextView teLogin;
    @BindView(R.id.auth_code)
    EditText auth_code;
    @BindView(R.id.zhuce)
    TextView zhuce;
    @BindView(R.id.forget_password)
    TextView forgetPassword;

    private CountDownTimer timer;//验证码倒计时
    private boolean isPassword = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        setHeaderTitle("用户登录");
        ButterKnife.bind(this);

        timer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long l) {
                getAuthCode.setText(l / 1000 + "秒后重试");
            }

            @Override
            public void onFinish() {
                getAuthCode.setText("重新发送");
                getAuthCode.setClickable(true);
            }
        };
        initdata();

        ViewUtils.setEditTextInhibitInputSpace(edPass);
    }

    private void initdata() {
        edHao.addTextChangedListener(this);
        edPass.addTextChangedListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }


    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        if (TextUtils.isEmpty(edHao.getText().toString())) {
            haoDelete.setVisibility(View.GONE);
        } else if (!TextUtils.isEmpty(edHao.getText().toString())) {
            haoDelete.setVisibility(View.VISIBLE);
        } else if (TextUtils.isEmpty(edPass.getText().toString())) {
            passDelete.setVisibility(View.GONE);
        } else if (!TextUtils.isEmpty(edPass.getText().toString())) {
            passDelete.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }

    @OnClick({R.id.hao_delete, R.id.pass_delete, R.id.tv_loginType, R.id.getAuthCode, R.id.te_login, R.id.zhuce, R.id.forget_password})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.hao_delete:                       //清空账号
                haoDelete.setVisibility(View.GONE);
                edHao.setText("");
                break;
            case R.id.pass_delete:                      //清空密码
                passDelete.setVisibility(View.GONE);
                edPass.setText("");
                break;
            case R.id.tv_loginType: //切换登录方式
                String s = tvLoginType.getText().toString();
                if ("验证码登录".equals(s)) {
                    tvLoginType.setText("密码登录");
                    ll_authCode.setVisibility(View.VISIBLE);
                    ll_password.setVisibility(View.GONE);
                    isPassword = false;
                    edHao.setInputType(InputType.TYPE_CLASS_NUMBER);
                } else if ("密码登录".equals(s)) {
                    tvLoginType.setText("验证码登录");
                    ll_authCode.setVisibility(View.GONE);
                    ll_password.setVisibility(View.VISIBLE);
                    isPassword = true;
                    edHao.setInputType(InputType.TYPE_CLASS_TEXT);
                }
                break;
            case R.id.getAuthCode:
                if (TextUtils.isEmpty(edHao.getText().toString())) {
                    ToastUtil.showToast("请输入手机号码");
                    break;
                }
                if (!Utils.isMobileNO(edHao.getText().toString())) {
                    ToastUtil.showToast("手机号码不正确");
                    break;
                }
                HashMap<String, String> map = new HashMap<>();
                map.put("phone", edHao.getText().toString());
                map.put("type", "2");
                HttpCom.POST(codeHandler, HttpCom.getYanzhengURL(), map, false);
                break;
            case R.id.te_login:                         //登录
                Login();
                break;
            case R.id.zhuce:                            //注册
                startActivityForResult(new Intent(this, RegisterActivity.class), 11);
                break;
            case R.id.forget_password:                  //忘记密码
                startActivity(new Intent(this, ForgetPassActivity.class));
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 11 && resultCode == 22) {
            finish();
        }
    }

    /**
     * 判断手机号发送验证码
     */
    Handler codeHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    try {
                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        int status = jsonObject.getInt("status");
                        String return_code = jsonObject.getString("return_code");
                        ToastUtil.showToast(return_code);
                        if (status == 1) {
                            //验证码发送成功
                            timer.start();
                            getAuthCode.setClickable(false);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Log.e("解析验证码异常", e.toString());
                    }
                    Log.e("发送验证码json", msg.obj.toString());
                    break;
                case 2:

                    break;
            }
        }
    };

    /**
     * 用户登录
     */
    private void Login() {
        String hao = edHao.getText().toString();
        String pass = edPass.getText().toString();
        String authCode = auth_code.getText().toString();
        if (hao.equals("")) {
            ToastUtil.showToast("请输入账号");
            return;
        }
        if (isPassword && pass.equals("")) {
            ToastUtil.showToast("请输入密码");
            return;
        }

        if (!isPassword && TextUtils.isEmpty(authCode)) {
            ToastUtil.showToast("请输入验证码");
            return;
        }

        HashMap<String, String> map = new HashMap<>();
        if (isPassword) {
            map.put("account", hao);
            String base64String = Utils.getBase64String(pass.getBytes(), DEFAULT_KEYS_DISABLE);
            map.put("password", base64String);
            HttpCom.POST(handler, HttpCom.getUserLoginURL(), map, false);
        } else {
            map.put("phone", hao);
            map.put("v_code", authCode);
            HttpCom.POST(handler, HttpCom.getUserCodeLoginURL(), map, false);
        }
    }

    /**
     * 登录的Handler
     */
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    int i = HttpUtils.DNSLogin(msg.obj.toString());
                    switch (i) {
                        case 1:
                            LoginActivity.this.finish();
                            break;
                        case -1000:
                            ToastUtil.showToast("用户不存在");
                            break;
                        case -1001:
                            ToastUtil.showToast("被禁用");
                            break;
                        case -10021:
                            ToastUtil.showToast("密码错误");
                            break;
                        case -1100:
                            ToastUtil.showToast("未知错误");
                            break;
                        case -97:
                            ToastUtil.showToast("验证码错误");
                            break;
                    }
                    break;
                case 2:

                    break;
            }
        }
    };
}
